#!/bin/bash

# QEMU K8s网络清理脚本

set -e

if [ "$EUID" -ne 0 ]; then
    echo "错误: 此脚本需要root权限运行"
    echo "请使用: sudo $0"
    exit 1
fi

echo "清理QEMU K8s网络配置..."

# 停止并删除网桥
if ip link show "k8s-br0" >/dev/null 2>&1; then
    echo "删除网桥: k8s-br0"
    ip link set "k8s-br0" down
    brctl delbr "k8s-br0"
fi

# 清理iptables规则
echo "清理iptables规则..."
DEFAULT_INTERFACE=$(ip route | grep default | awk '{print $5}' | head -n1)
if [ -n "$DEFAULT_INTERFACE" ]; then
    iptables -t nat -D POSTROUTING -s "192.168.100.0/24" -o "$DEFAULT_INTERFACE" -j MASQUERADE 2>/dev/null || true
    iptables -D FORWARD -i "k8s-br0" -o "$DEFAULT_INTERFACE" -j ACCEPT 2>/dev/null || true
    iptables -D FORWARD -i "$DEFAULT_INTERFACE" -o "k8s-br0" -j ACCEPT 2>/dev/null || true
fi

# 禁用并删除systemd服务
echo "删除systemd服务..."
systemctl disable qemu-k8s-network.service 2>/dev/null || true
rm -f "/etc/systemd/system/qemu-k8s-network.service"
rm -f "/etc/qemu-k8s-network.sh"
systemctl daemon-reload

echo "网络配置清理完成"
